package com.zhouchao.code.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhouchao.code.common.Result;
import com.zhouchao.code.domain.LagouAuthCode;
import com.zhouchao.code.feign.email.EmailServiceFeignClient;
import com.zhouchao.code.mapper.LagouAuthCodeMapper;
import com.zhouchao.code.service.ICodeService;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * @Author: zhouchao
 * @Date: 2021/10/16 20:19
 * @Description:
 */
@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @Autowired
    private LagouAuthCodeMapper lagouAuthCodeMapper;

    @Override
    public Result<Boolean> createCode(String email) {
        String code = RandomStringUtils.randomNumeric(6);

        LocalDateTime createtime = LocalDateTime.now();
        LocalDateTime expiretime = createtime.plus(1, ChronoUnit.MINUTES);

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(LocalDateTime.now());
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setExpiretime(expiretime);
        int i = lagouAuthCodeMapper.insert(lagouAuthCode);
        if (i > 0) {
            Result<Boolean> result = emailServiceFeignClient.sendEmail(email, code);
            return result;
        }
        return Result.failure("500", "验证码创建失败", null);
    }

    @Override
    public Result<Integer> validateCode(String email, String code) {
        LagouAuthCode lagouAuthCode = lagouAuthCodeMapper.selectOne(new QueryWrapper<LagouAuthCode>().lambda()
                .eq(LagouAuthCode::getEmail, email)
                .eq(LagouAuthCode::getCode, code));
        if (lagouAuthCode == null){
            return Result.success(1);
        }else if (lagouAuthCode.getExpiretime().isBefore(LocalDateTime.now())){
            return Result.success(2);
        }
        return Result.success(0);
    }


}
